package com.dhu.stylefit.util;

import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

@Component
public class PythonScriptRunner {

    public void runStyleAnalysis(Integer userId) {
        runScript(userId, null);
    }

    public void runStyleAnalysis(Integer userId, List<Integer> newClothesIds) {
        runScript(userId, newClothesIds);
    }

    private void runScript(Integer userId, List<Integer> newClothesIds) {
        try {
            // 使用 ClassPathResource 获取脚本文件
            ClassPathResource resource = new ClassPathResource("scripts/style_analyse2.py");
            File scriptFile = resource.getFile();
            String scriptPath = scriptFile.getAbsolutePath();
            
            ProcessBuilder processBuilder = new ProcessBuilder();

            if (newClothesIds != null && !newClothesIds.isEmpty()) {
                // 情况2：用户更新了衣服
                processBuilder.command("python", scriptPath, userId.toString(), newClothesIds.toString());
            } else {
                // 情况1：用户刚登录
                processBuilder.command("python", scriptPath, userId.toString());
            }

            Process process = processBuilder.start();
            
            // 读取输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 读取错误
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            while ((line = errorReader.readLine()) != null) {
                System.err.println(line);
            }

            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new RuntimeException("Python脚本执行失败，退出码: " + exitCode);
            }

        } catch (Exception e) {
            throw new RuntimeException("执行Python脚本时出错", e);
        }
    }
} 